import {
  HttpException,
  HttpStatus,
  Injectable,
  Query,
  Req,
} from '@nestjs/common';
import { CreateMessageDto } from './dto/message.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Message, User } from '../entities';
import { Repository } from 'typeorm';
import {
  AdminMessagePageReqDto,
  AdminMessagePageResDto,
} from './dto/admin-message.dto';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private readonly messageRepository: Repository<Message>,
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
  ) {}

  async create(user: User, data: CreateMessageDto) {
    const findUser = await this.usersRepository.findOne({
      where: { userId: user.userId, isDeleted: false },
    });
    if (!findUser) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    const createMessage = this.messageRepository.create({
      userId: user.userId,
      content: data.content,
    });

    return await this.messageRepository.save(createMessage);
  }

  async findAllForPage(
    query: AdminMessagePageReqDto,
  ): Promise<AdminMessagePageResDto> {
    const pageNo = query.pageNo || 1;
    const pageSize = query.pageSize || 10;

    const [list, total] = await this.messageRepository.findAndCount({
      where: { isDeleted: false },
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
    });

    return { list, total };
  }

  findOne(messageId: number) {
    return this.messageRepository.findOne({
      where: { messageId, isDeleted: false },
    });
  }

  // async reply(messageId: number, reply: string) {
  //   const findMessage = await this.messageRepository.findOne({
  //     where: { messageId, isDeleted: false },
  //   });
  //   if (!findMessage) {
  //     throw new HttpException('留言不存在', HttpStatus.BAD_REQUEST);
  //   }
  //   findMessage.reply = reply;
  //   this.messageRepository.save(findMessage);
  // }

  async fakeRemove(messageId: number) {
    const findMessage = await this.messageRepository.findOne({
      where: { messageId, isDeleted: false },
    });
    if (!findMessage) {
      throw new HttpException('食物不存在', HttpStatus.BAD_REQUEST);
    }
    findMessage.isDeleted = true;
    this.messageRepository.save(findMessage);
  }
}
